<template>
  <div id="tablecom" ref="height_page">
    <div class="form-block" ref="height_option">
      <!-- 添加分类 -->
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-plus"
        title="添加"
        @click="addClass"
        >添加</el-button
      >
      <!-- 删除选中 -->
      <el-button
        size="mini"
        type="danger"
        icon="el-icon-delete"
        title="删除"
        :disabled="deleteReadOnly"
        @click="deleteClass"
        >删除</el-button
      >
      <!-- 搜索分类输入框 -->
      <el-autocomplete
        class="inline-input search-input"
        prefix-icon="el-icon-search"
        clearable
        v-model="searchinput"
        :fetch-suggestions="querySearch"
        size="small"
        placeholder="请输入内容"
        :trigger-on-focus="true"
        @select="handleSelectInput"
      ></el-autocomplete>
    </div>
    <div ref="height_table" class="form-component__scroll">
      <!-- :default-sort 设置默认排序 height="600" -->
      <el-table
        ref="multipleTable"
        :height="tableHeight"
        :data="classList"
        tooltip-effect="dark"
        style="width: 100%"
        :default-sort="{ prop: 'date', order: 'descending' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          prop="id"
          label="序号"
          sortable
          width="80"
        ></el-table-column>
        <el-table-column
          prop="title"
          label="分类名称"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="parent_title"
          label="所属类型"
          width="120"
        ></el-table-column>
        <el-table-column label="类型图标" width="100">
          <template slot-scope="scope">
            <!-- {{scope.row.parent_icon}} -->
            <img
              :src="'./static/img/icon_tel_' + scope.row.parent_icon + '.png'"
              width="30"
              height="30"
              class="head_pic"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="add_time"
          label="添加日期"
          sortable
          width="150"
        ></el-table-column>
        <el-table-column
          prop="update_time"
          label="修改日期"
          sortable
        ></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeStatus(scope.$index, scope.row)"
            >
            </el-switch>
            {{ scope.row.status == 1 ? "启用" : "禁用" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.$index, scope.row)"
                title="编辑"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)"
                title="删除"
              ></el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div ref="height_paging">
      <paging
        :formconfig="formConfig"
        v-on:handle-current="listenCurrent"
        v-on:handle-size="listenSize"
        ref="mychild"
      ></paging>
    </div>

    <!-- 添加分类弹窗 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addClassVisible"
      :close-on-click-modal="false"
      top="25vh"
      width="440px"
      center
    >
      <div class="add-class-form">
        <el-form :model="addclassform" label-width="70px">
          <!-- 分类 -->
          <el-form-item prop="parent_id" label="选择类型">
            <el-select
              v-model="typename"
              size="small"
              @change="getTypeIcon"
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in typesList"
                :key="index"
                :label="item.title"
                :value="index"
              >
              </el-option>
            </el-select>
            <span class="icon"><img :src="typeicon" alt="" /></span>
          </el-form-item>
          <!-- 分类状态 -->
          <el-form-item prop="status" label="分类状态">
            <div class="clear_form">
              <el-switch
                v-model="addclassform.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
              <span>{{ addclassform.status ? "启用" : "禁用" }}</span>
            </div>
          </el-form-item>
          <el-form-item prop="title" label="分类名称">
            <el-input
              size="small"
              placeholder="请输入分类名称"
              v-model="addclassform.title"
              clearable
            >
            </el-input>
          </el-form-item>
          <div class="clear_form" v-if="addOrEdit">
            <el-switch
              v-model="addClassClear"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
            <!-- <input type="checkbox" v-model="addClass.Clear" :checked="addClassClear"> -->
            <span>{{
              addClassClear ? "清空数据关闭弹窗" : "保留数据继续添加"
            }}</span>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除分类 -->
    <el-dialog
      title="删除分类"
      :visible.sync="delClassVisible"
      :close-on-click-modal="false"
      top="25vh"
      width="440px"
      center
    >
      <div class="delete_msg" style="text-align: center">
        确认删除分类{{ deleteTitle }}吗？
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="delClassConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import paging from "@/components/paging";
// import Mock from '../mock'
import { getTypes, getClass, addCategory } from "../api/api";

export default {
  name: "tablecom",
  data() {
    return {
      sessionId: null, // 请求接口的验证ID
      addclassform: {}, // 添加分类表单数据
      addOrEdit: false,
      typesList: [], // 类型数据
      typeicon: "", // 选择类型图标
      typename: "", // 选择类型名称
      restaurants: [], // 分页器配置
      searchinput: "", // 搜索分类输入内容
      formConfig: {
        current: 1,
        length: 299,
        pagesizes: [20, 50, 100, 200],
        pagesize: 50,
        singlePage: false,
      },
      multipleSelection: [], // 选中的列表值
      tableHeight: 600, // 表格高度
      classList: [], // 分类列表
      deleteReadOnly: true, // 选择操作栏删除按钮 默认；只读状态
      addClassVisible: false, // 添加分类弹窗 默认；隐藏
      delClassVisible: false, // 删除分类弹窗 默认；隐藏
      deleteID: -1, // 删除分类 ID
      deleteTitle: "", // 删除分类名称
      addClassClear: false, // 清空表单 默认；不清空
    };
  },
  methods: {
    // 搜索输入框主函数
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      // console.log(restaurants)
      console.log(results);
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    // 搜索输入框模拟数据
    loadAll() {
      return [
        {
          value: "Mderci Paul时刻了",
          address: "上海市普陀区光复西路丹巴路28弄6号楼819",
        },
        {
          value: "Mdfsi发的时刻了",
          address: "上海市普陀区光复西路丹巴路28弄6号楼819",
        },
        {
          value: "M山王（西郊百联店）",
          address: "上海市长宁区仙霞西路88号第一层G05-F01-1-306",
        },
        {
          value: "M山王（西百联店）",
          address: "上海市长宁区仙霞西路88号第一层G05-F01-1-306",
        },
        { value: "M山", address: "上海市普陀区棕榈路" },
      ];
    },
    // 搜索输入框 显示数据点击返回
    handleSelectInput(item) {
      console.log(item);
    },
    // 表格删除按钮返回
    handleDelete(index, row) {
      console.log(row);
      this.delClassVisible = true; // 打开删除弹窗
      this.deleteID = row.id; // 分类id
      this.deleteTitle = row.title; // 分类名称
    },
    // 确认删除
    delClassConfirm() {
      // let deleteID = 999; // 模拟不存在的ID
      let deleteID = this.deleteID; // 删除分类ID
      let deleteConfig = { id: deleteID }; // 参数对象化
      addCategory(deleteConfig).then((data) => {
        // console.log(data);
        if (data.code == 4012) {
          this.$message({ message: data.msg, type: "error" });
        } else {
          let msg = "删除成功!"; // 提交返回成功
          this.getDataClass(); // 更新修改后的数据
          this.$message({ message: msg, type: "success" }); // 返回值
        }
        this.delClassVisible = false; // 关闭删除弹窗
      });
    },
    // 表格选中返回
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.deleteReadOnly = false;
      } else {
        this.deleteReadOnly = true;
      }
      console.log(this.multipleSelection);
    },
    // 批量删除分类
    deleteClass() {
      let that = this;
      if (!that.deleteReadOnly) {
        this.$message({ message: "批量删除分类", type: "success" }); // 删除请求，获取新数据
      }
    },
    // 获取、修改二级分类数据
    getCommitObj(rowData) {
      if (!this.addOrEdit) {
        // 编辑数据获取
        let { id, title, parent_id, parent_name, status } = rowData;
        this.addclassform = {
          id: id,
          title: title,
          introduce: "",
          parent_id: parent_id,
          status: status ? true : false,
        };
      } else {
        // 添加数据获取
        this.typename = ""; //去除一级分类名
        this.typeicon = ""; //去除一级分类icon
        this.addclassform = {
          title: "",
          parent_id: "",
          status: true,
          introduce: "",
        };
      }
    },
    // 添加分类弹窗
    addClass() {
      // 添加按钮给定
      this.addOrEdit = true;
      // 编辑数据获取
      this.getCommitObj();
      // 激活弹窗
      this.addClassVisible = true;
    },
    // 编辑按钮弹窗
    handleEdit(index, row) {
      // 编辑按钮给定
      this.addOrEdit = false;
      // 编辑数据获取
      this.getCommitObj(row);
      // 获取一级分类图标
      this.getTypeIcon(index);
      // 激活弹窗
      this.addClassVisible = true;
    },
    // 状态修改
    changeStatus(index, row) {
      // 编辑按钮给定
      this.addOrEdit = false;
      // 编辑数据获取
      this.getCommitObj(row);
      // 修改分类
      this.addClassConfirm();
    },
    // 选择类型的图标地址 赋值
    getTypeIcon(val) {
      this.addclassform.parent_id = this.typesList[val].id; //赋值二级分类父级ID
      this.typename = this.typesList[val].title;
      this.typeicon =
        "./static/img/icon_tel_" + this.typesList[val].icon + ".png";
    },
    // 修改分类确认按钮
    addClassConfirm() {
      if (this.addclassform.parent_id == "") {
        this.$message({ message: "请选择分类", type: "error" });
        return false;
      }
      if (this.addclassform.title == "") {
        this.$message({ message: "请填写标题", type: "error" });
        return false;
      }
      let formData = {
        title: this.addclassform.title, //获取二级分类名称
        parent_id: this.addclassform.parent_id, //获取二级分类父级ID
        status: this.addclassform.status == false ? 0 : 1,
        introduce: "213",
      };
      if (this.addclassform.id != undefined) {
        formData.id = this.addclassform.id;
      }
      // 提交表单数据
      console.log(formData);
      this.changeClassData(formData);
    },
    // 添加/修改二级分类请求
    changeClassData(formData) {
      addCategory(formData).then((data) => {
        // console.log(data);
        if (data.code == 4012) {
          this.$message({ message: data.msg, type: "error" });
        } else {
          // 提交返回成功
          let msg = "";
          // 判断 ‘编辑’|‘添加’ 操作进行请求
          if (!this.addOrEdit) {
            // 判断-编辑弹窗
            msg = "编辑成功";
            // 关闭弹窗
            this.addClassVisible = false;
          } else {
            // 判断-添加弹窗
            // 添加分类请求 返回成功执行
            if (this.addClassClear) {
              msg = "添加成功";
              // 关闭弹窗
              this.addClassVisible = false;
            } else {
              // 保留基本数据，清空分类名称 不关闭添加弹窗
              this.addclassform.title = "";
              msg = "添加成功，请继续添加";
            }
            // 更新修改后的数据
          }
          this.getDataClass();
          // 返回值
          this.$message({ message: msg, type: "success" });
        }
      });
    },
    // 获取时间戳
    getNowTime() {
      let that = this; //声明一个变量指向Vue实例this，保证作用域一致
      let nowTime = new Date();
      // 时间戳
      let timestamp = nowTime.getTime();
      // 标准时间
      let time = that.computeNowStandardTime(timestamp);
      // console.log(timestamp/1000,time);
      // 后台时间戳和前端相比差1000倍
      return timestamp / 1000;
    },
    // 获取 YY-MM-DD hh:mm 时间
    computeNowStandardTime(params) {
      let that = this; //声明一个变量指向Vue实例this，保证作用域一致
      let nowTime = new Date(params);
      let YY = that.appendZero(nowTime.getFullYear()); //年
      let MM = that.appendZero(nowTime.getMonth() + 1); //月
      let DD = that.appendZero(nowTime.getDate()); //日
      let hh = that.appendZero(nowTime.getHours()); //时
      let mm = that.appendZero(nowTime.getMinutes()); //分
      let ss = that.appendZero(nowTime.getSeconds()); //秒
      // 时间格式
      let time = YY + "-" + MM + "-" + DD + " " + hh + ":" + mm;
      // let time = YY +"-"+ MM +"-"+ DD +" "+ hh +":"+ mm +":"+ ss;
      return time;
    },
    //过滤加0
    appendZero(obj) {
      if (obj < 10) {
        return "0" + obj;
      } else {
        return obj;
      }
    },
    // 获取表格高度
    getTableHe() {
      // || this.$refs.height_option!=undefined || this.$refs.height_paging!=undefined
      if (this.$refs.height_page != undefined) {
        var pagetHe = this.$refs.height_page.offsetHeight;
        var optionHe = this.$refs.height_option.offsetHeight;
        var pagingHe = this.$refs.height_paging.offsetHeight;
        this.tableHeight = pagetHe - optionHe - pagingHe;
        // console.log(pagetHe,optionHe,pagingHe);
      }
    },
    getDataClass() {
      // 获取列表数据
      let that = this;
      getClass().then((data) => {
        // console.log(data)
        let { msg, code } = data;
        if (code == "200") {
          let dates = data.data;
          console.log(dates);
          this.classList = dates;
          this.formConfig.length = this.classList.length;
          this.formConfig.singlePage = this.classList.length <= 20;

          let classDate = that.classList;
          for (let index = 0; index < classDate.length; index++) {
            const element = classDate[index];
            element.add_time = that.computeNowStandardTime(
              element.add_time * 1000
            );
            element.update_time = that.computeNowStandardTime(
              element.update_time * 1000
            );
          }
        } else {
          this.$message({
            message: msg,
            type: "error",
          });
        }
      });
    },
    getDataTypes() {
      let that = this;
      getTypes().then((data) => {
        // console.log(data)
        let { msg, code } = data;
        if (code == "200") {
          let dates = data.data;
          console.log(dates);
          that.typesList = dates;
        } else {
          that.$message({
            message: msg,
            type: "error",
          });
        }
      });
    },
    // 分页 数量返回
    listenCurrent(something) {
      this.pageNum = something;
      // this._synchron();
      console.log(this.pageNum);
    },
    // 分页页码改变时的返回
    listenSize(something) {
      this.pageNum = something;
      // this._synchron();
      console.log(this.pageNum);
    },
    // 切换页码时请求数据
    // handleSizeChange(val) {
    //   console.log(`每页 ${val} 条`);
    //   var _this = this,item = {index: 1,date: "2016-05-02",name: "王小虎",address: "上海市普陀区金沙江路 1518 弄"};
    //   _this.tableData = Array(_this.formConfig.pagesize).fill(item);
    // },
    // handleCurrentChange(val) {
    //   console.log(`当前页: ${val}`);
    // },
    // 选中及取消
    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },
  },
  mounted() {
    let that = this;
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      // 搜索模拟数据
      this.restaurants = this.loadAll();
      // 表格高度
      this.getTableHe();
      setTimeout(() => {
        this.getTableHe();
      }, 1000);
    });
    window.addEventListener("resize", this.getTableHe, false);
  },
  updated() {
    var that = this;
  },
  created() {
    var that = this;
    // 获取参数
    // let ParamsKey = that.$route.params.key;
    // console.log(ParamsKey);

    // 获取请求接口的user ID
    that.sessionId = sessionStorage.getItem("access-token");
    console.log(that.sessionId);
    let paramsType = { sessionId: that.sessionId };

    // 提供模拟的请求接口
    // Mock.datatype();
    // 获取一级分类数据
    that.getDataTypes();
    // 获取二级分类数据
    that.getDataClass();
  },
  computed: {
    returnStatus: function () {
      return this.addclassform.status == 1 ? true : false;
    },
  },
  components: {
    paging: paging,
  },
};
</script>
